/**
 * PC页面初始化脚本 [v0.0.1] 不需要手工引入，已经压缩内嵌到公共的头部
 * 功能：初始化页面的REM，检测是否支持webp
 * 支持webp html添加class名称 `webp` localStorage与cookie中写入 support-webp=1
 * 不支持webp localStorage与cookie中写入 support-webp=0
 * 对外提供的变量与方法：
 *   window.docH, window.docW, window.rem, window.px2rem, window.rem2px
 *   mTools.supportWebp(fn(support))
 *   mTools.log(msg, data);
 */
;(function(window, document, undefined){
  var mTools = {}, win=window, doc = document, ua = window.navigator.userAgent;

  mTools.initREM = function(size){
    var docEl = doc.documentElement;
    var size = size || 750;

    var resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize';
    win.docH = docEl.clientHeight;
    win.docW = docEl.clientWidth;
    var matches = ua.match(/Android[\S\s]+AppleWebkit\/(\d{3})/i);
    var UCversion = ua.match(/U3\/((\d+|\.){5,})/i);
    var isUCHd = UCversion && parseInt(UCversion[1].split('.').join(''), 10) >= 80;
    var isIos = navigator.appVersion.match(/(iphone|ipad|ipod)/gi);
    let dpr = win.devicePixelRatio || 1;
    if (!isIos && !(matches && matches[1] > 534) && !isUCHd) {
      // 如果非iOS, 非Android4.3以上, 非UC内核, 就不执行高清, dpr设为1;
      dpr = 1;
    }
    win.dpr = Math.floor(dpr) || 1;

    win.px2rem = function(n){ return parseFloat(n) / win.rem; }
    win.rem2px = function(n){ return parseFloat(n) * win.rem; }
    docEl.style.opacity=0;
    docEl.setAttribute('data-dpr', win.dpr);
    var recalc = function () {
          win.docH = docEl.clientHeight;
          win.docW = docEl.clientWidth;
          var clientWidth = win.docW || 320;
          var docCls = docEl.classList;
          var fontSize = (clientWidth < 320 ? 320 : clientWidth > size ? size : clientWidth)/10;
          win.rem = fontSize * win.dpr;
          docEl.style.fontSize = win.rem + 'px';
          docEl.style.opacity = 1;
    };

    // 移动端绑定 orientationchange 事件，PC上绑定 resize 事件
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);

    // 设置Viewport
    const scale = 1 / dpr;
    let metaEl = doc.querySelector('meta[name="viewport"]');
    if (!metaEl) {
      metaEl = doc.createElement('meta');
      metaEl.setAttribute('name', 'viewport');
      doc.head.appendChild(metaEl);
    }
    metaEl.setAttribute('content', `width=device-width,user-scalable=no,initial-scale=${scale},maximum-scale=${scale},minimum-scale=${scale}`);
  }

  mTools.supportWebp = function(callback){
    if(!window.localStorage) callback(false);

    callback = callback || function(){};
    if(localStorage.getItem('support-webp')==='1'){
      document.documentElement.classList.add('webp');
      return callback(true);
    }

    var image = new Image();
    image.onerror = function(){
      localStorage.setItem('support-webp','0');
      callback(false);
    };
    image.onload = function(){
      if(image.width == 1){
        document.documentElement.classList.add('webp');
        localStorage.setItem('support-webp','1');
        document.cookie = "support-webp=1; max-age=31536000; domain="
        callback(true);
      }else{
        localStorage.setItem('support-webp','0');
        callback(false);
      }
    };
    image.src = '';
  }
  mTools.log = function(errmsg, data){
    var oLogBox= doc.getElementById('logBox');
    if(!oLogBox){
      oLogBox = doc.createElement('div');
      oLogBox.id = 'logBox';
      oLogBox.style.cssText = "position: fixed; bottom: 0px; left: 0px; right: 0px; top: auto; word-break: break-all; background: rgb(249, 204, 204); font-size: 14px; color: red; padding: 20px 10px;"
      doc.body.appendChild(oLogBox);
    }
    oLogBox.innerHTML += errmsg+(data && JSON.stringify(data) || '')+'<br/>';
  }

  mTools.initREM(750);
  mTools.supportWebp();
  window.mTools = mTools;
})(window, document);


//
!(function(window, document, undefined){
  var mTools = {}, win=window, doc = document;

  mTools.supportWebp = function(callback){
    if(!win.localStorage) callback(false);

    callback = callback || function(){};
    if(localStorage.getItem('support-webp')==='1'){
      doc.documentElement.classList.add('webp');
      return callback(true);
    }

    var image = new Image();
    image.onerror = function(){
      localStorage.setItem('support-webp','0');
      callback(false);
    };
    image.onload = function(){
      if(image.width == 1){
        doc.documentElement.classList.add('webp');
        localStorage.setItem('support-webp','1');
        doc.cookie = "support-webp=1; max-age=31536000; domain="
        callback(true);
      }else{
        localStorage.setItem('support-webp','0');
        callback(false);
      }
    };
    image.src = '';
  }

  var logBoxId = 'log_box_1024';
  var logBoxTimer = null;
  mTools.log = function(errmsg, data){
    var oLogBox= doc.getElementById(logBoxId);
    clearTimeout(logBoxTimer);
    if(!oLogBox){
      oLogBox = doc.createElement('div');
      oLogBox.id = logBoxId;
      oLogBox.style.cssText = "position: fixed; z-index:9999; bottom: 0px; left: 0px; right: 0px; top: auto; word-break: break-all; background: rgb(249, 204, 204); font-size: 24px; color: red; padding: 20px 10px;"
      doc.body.appendChild(oLogBox);
    }
    oLogBox.style.display = 'block';
    oLogBox.innerHTML = errmsg+(data && JSON.stringify(data) || '')+'<br/>';

    logBoxTimer = setTimeout(function(){
      mTools.log.hide();
    }, 4000);
  }
  mTools.log.hide = function(){
    var el = doc.getElementById(logBoxId);
    el && (el.style.display = 'none');
  }

  mTools.supportWebp();
  win.mTools = mTools;
})(window, document);
